package com.ruoyi.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.model.user.UserVO;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.UserContext;
import com.ruoyi.user.service.IUserCacheService;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import java.util.Arrays;

@Component
public class AppInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserCacheService userCacheService;

    private static final String NOT_LOGIN_URL[] = {"/app/user/login", "/app/user/add"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // APP登录接口放开
        boolean isNotLogin = Arrays.stream(NOT_LOGIN_URL).filter(url -> request.getRequestURI().contains(url)).findFirst().isPresent();
        if(isNotLogin){
            return true;
        }
        // 校验token
        String token = request.getHeader(Constants.TOKEN);
        if(StrUtil.isBlank(token)){
            AjaxResult ajaxResult = AjaxResult.error("用户未登录，请重新登录");
            ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
            return false;
        }
        UserVO userVO = userCacheService.getUser(token);
        if(ObjectUtil.isNull(userVO)){
            AjaxResult ajaxResult = AjaxResult.error("用户未登录，请重新登录");
            ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
            return false;
        }
        UserContext.set(userVO);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        UserContext.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        UserContext.remove();
    }
}
